package cn.com.server.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.com.server.common.AjaxCodeUtil;
import cn.com.server.common.AjaxObject;
import cn.com.server.service.GroupService;
import cn.com.server.service.RoleService;
import cn.com.server.service.UserService;
import cn.com.server.extend.model.RegisterSaveModel;

@Controller
@RequestMapping("register")
public class RegisterController {
	
	@Autowired
	private GroupService groupService;
	
	@Autowired
	private RoleService roleService;
	
	@Autowired
	private UserService userService;
	
	
	@RequestMapping("/register")
	public String index(HttpServletRequest request, HttpServletResponse response) {
		return "register";
	}
	
	@RequestMapping("/getGroupList")
	@ResponseBody
	public AjaxObject getGroupList(HttpServletRequest request, HttpServletResponse response) {
		return new AjaxObject(0,"",groupService.selectByRegisterFlg(true));
	}
	
	@RequestMapping("/getRoleList")
	@ResponseBody
	public AjaxObject getRoleList(Long groupId,HttpServletRequest request, HttpServletResponse response) {
		return new AjaxObject(0,"",roleService.selectByGroupId(groupId));
	}
	
	/**
	 * 此接口不能添加WEB管理员用户
	 * @param registerSaveModel
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/save")
	@ResponseBody
	public AjaxObject save(RegisterSaveModel registerSaveModel,HttpServletRequest request, HttpServletResponse response,HttpSession session) {
		try {
			if(registerSaveModel.getName()==null||"".equals(registerSaveModel.getName())) {
				return AjaxCodeUtil.getAjaxObject("userNameException");
			}
			if(userService.selectByName(registerSaveModel.getName())!=null) {
				return AjaxCodeUtil.getAjaxObject("userExistException");
			}
			if(registerSaveModel.getPassword()==null||"".equals(registerSaveModel.getPassword())) {
				return AjaxCodeUtil.getAjaxObject("passwordException");
			}
			if(registerSaveModel.getIp()==null||"".equals(registerSaveModel.getIp())) {
				return AjaxCodeUtil.getAjaxObject("ipException");
			}
			if(registerSaveModel.getRoleId()==null) {
				return AjaxCodeUtil.getAjaxObject("roleIdException");
			}
			if(userService.insertUserAndTerminalAndUserRole(registerSaveModel)>0) {
				return AjaxCodeUtil.getAjaxObject("success");
			}else {
				return AjaxCodeUtil.getAjaxObject("saveException");
			}
		} catch (Exception e) {
			e.printStackTrace();
			return AjaxCodeUtil.getAjaxObject("saveException");
		}
	} 
}
